package com.gmadmin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmadmin.entity.SysMenu;
import com.gmadmin.entity.SysRole;
import com.gmadmin.entity.vo.api.SysApiVo;
import com.gmadmin.entity.vo.menu.SysMenuVo;
import com.gmadmin.exception.RoleException;
import com.gmadmin.mapper.SysRoleMapper;
import com.gmadmin.payload.RoleQueryCriteria;
import com.gmadmin.service.SysApiService;
import com.gmadmin.service.SysMenuService;
import com.gmadmin.service.SysRoleService;


import com.gmadmin.entity.vo.role.SysRoleVo;
import com.gmadmin.utils.CollectionBeanUtils;
import com.gmadmin.vo.PageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author zhangliang
 * @version 1.0
 * @date 2021/2/2 16:01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    private final SysMenuService menuService;

    private  final SysApiService apiService;


    protected Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Lazy
    public SysRoleServiceImpl(SysMenuService menuService, SysApiService apiService) {
        this.menuService = menuService;
        this.apiService = apiService;
    }


    @Override
    public List<SysRoleVo> selectByUserId(Long id) {
        List<SysRole> sysRoles = baseMapper.findRoleByUserId(id);
        return BeanUtil.copyToList(sysRoles, SysRoleVo.class);
    }

    @Override
    public List<SysRoleVo> getRoles() {
        List<SysRole> roles = baseMapper.selectList(null);
        return CollectionBeanUtils.copyListProperties(roles, SysRoleVo::new);
    }

    @Override
    public List<SysRoleVo> getByUserId(Long userId) {
        List<SysRole> sysRoles = baseMapper.findRoleByUserId(userId);
        return CollectionBeanUtils.copyListProperties(sysRoles, SysRoleVo::new);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public PageVo<SysRoleVo> findListByPage(RoleQueryCriteria queryCriteria, Page<SysRole> page) {

        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("role_id");


        IPage<SysRole> iPage = baseMapper.findListByPage(page, queryWrapper);


        List<SysRole> sysRoles = iPage.getRecords();
        System.out.println(sysRoles);

        List<SysRoleVo> sysRoleVos = new ArrayList<>();
//        處理返回的菜單数据
        sysRoles.forEach(sysRole -> {
            List<SysMenu> menus = menuService.findListByRoleId(sysRole.getId());
            List<SysMenuVo> sysMenuVos = CollectionBeanUtils.copyListProperties(menus, SysMenuVo::new);
            SysRoleVo sysRoleVo = new SysRoleVo();
            BeanUtils.copyProperties(sysRole, sysRoleVo);

           List<SysApiVo> apiVos=apiService.findListByRoleId(sysRole.getId());

            sysRoleVo.setMenus(sysMenuVos);
            sysRoleVo.setMenuIds(sysMenuVos.stream().map(SysMenuVo::getId).collect(Collectors.toList()));

            sysRoleVo.setApis(apiVos);
            sysRoleVo.setApiIds(apiVos.stream().map(SysApiVo::getId).collect(Collectors.toList()));

            sysRoleVos.add(sysRoleVo);

        });

        PageVo<SysRoleVo> pageVo = new PageVo<>(sysRoleVos, iPage.getTotal());
        return pageVo;

    }

    @Transactional(rollbackFor = RoleException.class)
    @Override
    public void updateRoleAndMenus(Long roleId, List<Long> menuIds) {
        baseMapper.deleteRoleAndMenus(roleId);
        if (!CollectionUtils.isEmpty(menuIds)) baseMapper.insertRoleAndMenus(roleId,menuIds);
    }

    @Override
    public void updateRoleAndApis(Long roleId, List<Long> apiIds) {
        baseMapper.deleteRoleAndApis(roleId);
        if (!CollectionUtils.isEmpty(apiIds)) baseMapper.insertRoleAndApis(roleId,apiIds);
    }

    ////    @Override
////    public SysRoleVo getByRoleId(Serializable id) {
////        SysRole sysRole = sysRoleMapper.selectById(id);
////        List<MenuDto> menuDtoList = sysRole.getMenus().stream().map(MenuDto::buildMenuDto).collect(Collectors.toList());
////        SysMenuVo sysMenuVo = new SysMenuVo();
////        List<SysMenuVo> menuVos = menuDtoList.stream().map(sysMenuVo::buildMenu).collect(Collectors.toList());
////
////
////        SysRoleVo sysRoleVo = Builder.of(SysRoleVo::new)
////                .with(SysRoleVo::setId, sysRole.getId())
////                .with(SysRoleVo::setName, sysRole.getName())
////                .with(SysRoleVo::setLevel, sysRole.getLevel())
////                .with(SysRoleVo::setDescription, sysRole.getDescription())
////                .with(SysRoleVo::setDataScope, sysRole.getDataScope())
////                .with(SysRoleVo::setCreateBy, sysRole.getCreateBy())
////                .with(SysRoleVo::setUpdateBy, sysRole.getUpdateBy())
////                .with(SysRoleVo::setMenus, menuVos)
////                .with(SysRoleVo::setCreateTime, Objects.nonNull(sysRole.getCreateTime()) ? sysRole.getCreateTime() : null)
////                .with(SysRoleVo::setUpdateTime, Objects.nonNull(sysRole.getUpdateTime()) ? sysRole.getUpdateTime() : null)
////                .build();
//
////        LogUtil.debug("根据id返回: "+JSONUtil.toJsonStr(sysRoleVo));
////        return sysRoleVo;
////    }
//
//    @Override
//    public void download(HttpServletResponse response, List<Long> ids) throws IOException {
//        List<SysRole> sysRoles = sysRoleMapper.findAll(ids);
//        List<Map<String, Object>> mapList = new ArrayList<>();
//
//        for (SysRole role : sysRoles
//        ) {
//            Map<String, Object> map=new HashMap<>();
//            map.put("角色id",role.getId());
//            map.put("角色名称",role.getName());
//            map.put("角色等级",role.getLevel());
//            map.put("角色描述",role.getDescription());
//            map.put("权限范围",role.getDataScope());
//            map.put("关联菜单",role.getMenus());
//            map.put("创建于",role.getCreateTime());
//            map.put("创建时间",role.getCreateTime());
//            map.put("更新于",role.getUpdateBy());
//            map.put("更新时间",role.getUpdateTime());
//            mapList.add(map);
//        }
//
//        FileUtil.downloadExcel(mapList, response);
//    }
//
//    @Override
//    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
//    public Boolean addRole(SysRole sysRole, List<SysMenu> menus) {
//        sysRoleMapper.insert(sysRole);
//        sysRoleMapper.insertRoleConnectedMenus(sysRole.getId(), menus);
//        return true;
//    }
//
//    @Override
//    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
//    public Boolean delRole(Set<Long> ids) {
//        sysRoleMapper.deleteBatchIds(ids);
//        sysRoleMapper.deleteRoleConnectedMenus(ids);
//        sysRoleMapper.deleteRoleConnectedUsers(ids);
//        return true;
//    }
//
//    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
//    @Override
//    public Boolean updateRole(SysRole sysRole) {
//        sysRoleMapper.updateById(sysRole);
//        Set<Long> ids = new HashSet<>();
//        ids.add(sysRole.getId());
//        sysRoleMapper.deleteRoleConnectedMenus(ids);
//        if (sysRole.getMenus().size() > 0) {
//            sysRoleMapper.insertRoleConnectedMenus(sysRole.getId(), sysRole.getMenus());
//        }
//        return true;
//    }


}
